import axios from "axios";
import { ElMessage } from "element-plus";
import { useStore } from "@/stores";
const store = useStore();
// import { useI18n } from "vue-i18n";
// const { t } = useI18n();
import { useRouter } from "vue-router";
/**
 * axios封装
 */
const http = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    withCredentials: true,
    timeout: 60000,
    headers: {
        "X-Requested-With": "XMLHttpRequest",
    },
});
/**
 * 请求拦截器
 */
http.interceptors.request.use(
    (config) => {
        // 请求携带token
        const token = store.token;
        if (token) {
            config.headers["Authorization"] = token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
/**
 * 响应拦截器
 */
http.interceptors.response.use(
    (response) => {
        const data = response.data;
        if (data.success) {
            return data;
        } else {
            ElMessage.error(data.msg);
            errorHandler(data);
            return Promise.reject(data);
        }
    },
    (error) => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    ElMessage.error("登录状态已过期，请重新登录！");
                    break;
                case 403:
                    ElMessage.error("当前用户无此操作权限！");
            }
        }
    }
);
/**
 * 错误处理
 */
const errorHandler = (error: any) => {
    console.log(error);
    if (error.msg) {
        switch (error.msg) {
            case 400:
                ElMessage.error("请求错误");
                break;
            case "Unauthorized":
                // ElMessage.error("登录状态已过期，请重新登录！");

                const router = useRouter();
                store.user.token = "";
                store.user.userInfo = {};
                console.log(router);
                router.replace("/");
                router.clearRoutes();
                sessionStorage.clear();
                setTimeout(() => {
                    location.reload();
                }, 100);

                break;
            case 403:
                ElMessage.error("当前用户无此操作权限！");
        }
    }
};
export default http;
